<template>
  <el-dialog
    :visible="visible"
    :append-to-body="true"
    :width="$store.state.isAdmin ? '1200px' : '500px'"
    @close="$emit('update:visible', false)"
    class="c-LotteryConfig"
  >
    <div class="c-LotteryConfigtitle" slot="title">
      <span :style="{ fontSize: '16px', marginRight: '20px' }">
        抽奖配置
      </span>
      <el-button size="mini" @click="addLottery">增加奖项</el-button>
      <el-button size="mini" type="primary" @click="onSubmit">保存配置</el-button>
      <el-button size="mini" @click="$emit('update:visible', false)">取消</el-button>
    </div>

    <div class="config-container">
      <!-- 左侧抽奖配置 -->
      <div class="left-config" :class="{ 'full-width': !$store.state.isAdmin }">
        <div class="container">
          <el-form ref="form" :model="form" size="mini">
            <el-form-item label="抽奖标题">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="抽奖总人数">
              <el-input
                type="number"
                v-model="form.number"
                :min="1"
                :max="list.length"
                :step="1"
              ></el-input>
              <div class="form-tip" v-if="list.length">
                已导入 {{ list.length }} 人
              </div>
            </el-form-item>
            <el-form-item>
              <div class="prize-item">
                <div class="prize-name">
                  <span>{{ form.firstPrizeName || '一等奖' }}</span>
                  <el-popover
                    placement="right"
                    width="200"
                    trigger="click"
                    v-model="showFirstPrizeEdit"
                  >
                    <el-input 
                      v-model="form.firstPrizeName" 
                      size="mini" 
                      placeholder="请输入奖项名称"
                    >
                      <el-button 
                        slot="append" 
                        icon="el-icon-check" 
                        @click="showFirstPrizeEdit = false"
                      ></el-button>
                    </el-input>
                    <i 
                      slot="reference" 
                      class="el-icon-edit edit-icon"
                    ></i>
                  </el-popover>
                </div>
                <div class="prize-input">
                  <el-input
                    type="number"
                    v-model="form.firstPrize"
                    :min="0"
                    :step="1"
                  ></el-input>
                </div>
              </div>
            </el-form-item>
            <el-form-item
              v-for="newitem in storeNewLottery"
              :key="newitem.key"
            >
              <div class="prize-item">
                <div class="prize-name">{{ newitem.name }}</div>
                <div class="prize-input">
                  <el-input
                    type="number"
                    :min="0"
                    :step="1"
                    v-model="form[newitem.key]"
                    @change="
                      val => {
                        form[newitem.key] = Number(val);
                      }
                    "
                  ></el-input>
                  <i 
                    class="el-icon-delete delete-icon" 
                    @click="deletePrize(newitem)"
                  ></i>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 右侧配置区域 -->
      <div v-if="$store.state.isAdmin" class="right-preset">
        <div class="preset-container">
          <!-- 预设中奖配置 -->
          <div class="preset-winners-config">
            <!-- 预设中奖的标题和按钮 -->
            <div class="preset-header">
              <h3>预设中奖名单</h3>
              <div class="preset-actions">
                <div class="prize-quotas">
                  <el-tooltip 
                    v-for="prize in allPrizes" 
                    :key="prize.key"
                    :content="`${prize.name}: 已预设${prize.used}/${prize.total}人`"
                    placement="top"
                  >
                    <el-tag size="small" :type="prize.used >= prize.total ? 'danger' : ''">
                      {{ prize.name }}: {{ prize.used }}/{{ prize.total }}
                    </el-tag>
                  </el-tooltip>
                </div>
                <el-button 
                  type="primary" 
                  icon="el-icon-plus"
                  @click="showPresetDialog"
                  :disabled="!list.length || !hasAvailablePrizes"
                >
                  添加预设
                </el-button>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete"
                  @click="clearPresetWinners"
                  :disabled="!presetWinnersList.length"
                >
                  清空
                </el-button>
              </div>
            </div>

            <!-- 预设中奖列表 -->
            <div v-if="!presetWinnersList.length" class="empty-state">
              <i class="el-icon-tickets"></i>
              <p>暂无预设中奖名单</p>
              <div class="empty-actions">
                <template v-if="!list.length">
                  <span class="warning-text">请先导入名单</span>
                  <el-button type="primary" size="small" @click="goToImportList">去导入</el-button>
                </template>
                <template v-else-if="!availablePrizes.length">
                  <span class="warning-text">请先添加奖项</span>
                  <el-button type="primary" size="small" @click="addLottery">去添加</el-button>
                </template>
                <template v-else>
                  <el-button type="primary" icon="el-icon-plus" @click="showPresetDialog">添加预设</el-button>
                </template>
              </div>
            </div>

            <el-table 
              v-else
              :data="presetWinnersList"
              style="width: 100%"
              border
            >
              <el-table-column prop="number" label="员工姓名" width="150">
                <template slot-scope="scope">
                  <div class="person-info">
                    <span class="info">{{ scope.row.number }} {{ getPersonInfo(scope.row.number).name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="prizes" label="预设奖项">
                <template slot-scope="scope">
                  <el-tag 
                    v-for="prize in getPrizeNames(scope.row.prizes)" 
                    :key="prize"
                    size="small"
                    class="prize-tag"
                  >
                    {{ prize }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center">
                <template slot-scope="scope">
                  <el-button 
                    type="text" 
                    icon="el-icon-delete"
                    @click="removePreset(scope.row.number)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 排除名单配置 -->
          <div class="excluded-list-config">
            <div class="preset-header">
              <div class="header-title">
                <h3>排除名单</h3>
                <el-tooltip placement="right">
                  <div slot="content">
                    <div v-for="prize in allPrizes" :key="prize.key">
                      {{ prize.name }}: {{ getExcludedCount(prize.key) }} 人
                    </div>
                  </div>
                  <span class="excluded-total">
                    (已排除: {{ totalExcludedCount }} 人)
                  </span>
                </el-tooltip>
              </div>
              <div class="preset-actions">
                <el-button 
                  type="primary" 
                  icon="el-icon-plus"
                  @click="showExcludedDialog"
                  :disabled="!list.length"
                >
                  添加排除
                </el-button>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete"
                  @click="clearExcludedList"
                  :disabled="!hasExcludedPeople"
                >
                  清空
                </el-button>
              </div>
            </div>
            
            <div v-if="!hasExcludedPeople" class="empty-state">
              <i class="el-icon-warning-outline"></i>
              <p>暂无排除名单</p>
            </div>
            
            <el-table v-else :data="allExcludedListData" style="width: 100%" border>
              <el-table-column prop="prize" label="奖项">
                <template slot-scope="scope">
                  {{ getPrizeName(scope.row.prize) }}
                </template>
              </el-table-column>
              <el-table-column prop="number" label="员工姓名" width="150">
                <template slot-scope="scope">
                  <div class="person-info">
                    <span class="info">{{ scope.row.number }} {{ getPersonInfo(scope.row.number).name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center">
                <template slot-scope="scope">
                  <el-button 
                    type="text" 
                    icon="el-icon-delete"
                    @click="removeExcluded(scope.row.prize, scope.row.number)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>

    <!-- 增加奖项对话框 -->
    <el-dialog
      :visible.sync="showAddLottery"
      :append-to-body="true"
      width="300px"
      class="dialog-showAddLottery"
    >
      <div class="add-title" slot="title">增加奖项</div>
      <el-form ref="newLottery" :model="newLottery" size="mini">
        <el-form-item label="奖项名称">
          <el-input v-model="newLottery.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addHandler">增加奖项</el-button>
          <el-button @click="showAddLottery = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加预设对话框 -->
    <el-dialog 
      title="添加预设中奖" 
      :visible.sync="presetDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form 
        v-if="list.length" 
        :model="presetForm"
        label-width="80px"
        :rules="presetRules"
        ref="presetForm"
      >
        <el-form-item label="预设奖项" prop="prizes">
          <el-select 
            v-model="presetForm.prizes" 
            placeholder="请选择预设奖项"
            style="width: 100%"
          >
            <el-option 
              v-for="prize in availablePrizes"
              :key="prize.key"
              :label="`${prize.name} (剩余${prize.total - prize.used}名额)`"
              :value="prize.key"
              :disabled="prize.used >= prize.total"
            >
              <span style="float: left">{{ prize.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                剩余: {{ prize.total - prize.used }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择员工" prop="numbers">
          <el-select 
            v-model="presetForm.numbers" 
            multiple
            filterable 
            :multiple-limit="getMaxSelectCount"
            placeholder="请选择员工(可多选)"
            :disabled="!presetForm.prizes.length"
            style="width: 100%"
          >
            <el-option
              v-for="item in availableList"
              :key="item.key"
              :label="`${item.key} ${item.name}`"
              :value="item.key"
            >
              <span style="float: left">{{ item.key }} {{ item.name }}</span>
            </el-option>
          </el-select>
          <div class="form-tip">
            <template v-if="presetForm.prizes.length">
              当前可选 {{ getMaxSelectCount }} 名员工
            </template>
            <template v-else>
              <span class="warning-text">请先选择预设奖项</span>
            </template>
          </div>
        </el-form-item>
      </el-form>
      <div v-else class="empty-tip">
        <i class="el-icon-warning-outline"></i>
        <p>请先导入名单后再设置预中奖</p>
        <el-button type="primary" @click="goToImportList">去导入名单</el-button>
      </div>
      <div slot="footer">
        <el-button @click="presetDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitPresetForm"
          :disabled="!list.length || !availablePrizes.length"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 添加排除对话框 -->
    <el-dialog 
      :visible.sync="excludedDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <div slot="title" class="dialog-title">
        <span>添加排除名单</span>
        <el-tooltip placement="right">
          <div slot="content">
            <div v-for="prize in allPrizes" :key="prize.key">
              {{ prize.name }}: {{ getExcludedCount(prize.key) }} 人
            </div>
          </div>
          <span class="excluded-count">
            (已排除: {{ totalExcludedCount }} 人)
          </span>
        </el-tooltip>
      </div>
      <el-form v-if="list.length">
        <el-form-item label="排除奖项">
          <el-select 
            v-model="excludedForm.prize" 
            placeholder="请选择要排除的奖项"
            style="width: 100%"
          >
            <el-option 
              v-for="prize in allPrizes"
              :key="prize.key"
              :label="prize.name"
              :value="prize.key"
            >
              <span style="float: left">{{ prize.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择员工">
          <el-select
            v-model="excludedForm.numbers"
            multiple
            filterable
            placeholder="选择不参与抽奖的员工"
            :multiple-limit="currentPrizeMaxExcluded"
            style="width: 100%"
            :disabled="!excludedForm.prize"
          >
            <el-option
              v-for="item in availableExcludedList"
              :key="item.key"
              :label="`${item.key} ${item.name}`"
              :value="item.key"
            >
              <span style="float: left">{{ item.key }} {{ item.name }}</span>
            </el-option>
          </el-select>
          <div class="form-tip" v-if="excludedForm.prize">
            <template v-if="currentPrizeMaxExcluded > 0">
              已选择 {{ excludedForm.numbers.length }} 人
              <span :class="{ 'warning-text': isExceedLimit }">
                (最多可排除 {{ currentPrizeMaxExcluded }} 人)
              </span>
            </template>
            <template v-else>
              <span class="warning-text">该奖项不能排除任何人</span>
            </template>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="excludedDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExcludedForm">确定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>
<script>
import { setData, configField } from '@/helper/index';
import { randomNum } from '@/helper/algorithm';
export default {
  name: 'LotteryConfig',
  props: {
    visible: Boolean
  },
  computed: {
    form: {
      get() {
        return this.$store.state.config;
      },
      set(val) {
        return val;
      }
    },
    storeNewLottery() {
      return this.$store.state.newLottery;
    },
    list() {
      return this.$store.state.list;
    },
    presetWinnersList() {
      const presetWinners = this.$store.state.presetWinners;
      return Object.entries(presetWinners).map(([number, prizes]) => ({
        number,
        prizes
      }));
    },
    availablePrizes() {
      const prizes = [
        { 
          key: 'firstPrize', 
          name: '一等奖',
          total: this.form.firstPrize,
          used: (this.$store.state.presetWinners ? 
            Object.values(this.$store.state.presetWinners)
              .filter(prizes => prizes.includes('firstPrize')).length : 0)
        }
      ];
      
      // 添加自定义奖项
      this.storeNewLottery.forEach(item => {
        const used = this.$store.state.presetWinners ? 
          Object.values(this.$store.state.presetWinners)
            .filter(prizes => prizes.includes(item.key)).length : 0;
        prizes.push({
          key: item.key,
          name: item.name,
          total: this.form[item.key],
          used: used
        });
      });
      
      // 只返回还有剩余名额的奖项
      return prizes.filter(prize => prize.used < prize.total);
    },
    hasPresetPermission() {
      return localStorage.getItem('isAdmin') === 'true';
    },
    availableList() {
      // 过滤掉已经预设了当前奖项的人员
      const currentPrize = this.presetForm.prizes;
      return this.list.filter(person => {
        // 如果这个人已经有预设奖项了
        if (this.presetWinnersList.find(winner => winner.number === person.key)) {
          const winner = this.presetWinnersList.find(w => w.number === person.key);
          // 检查是否预设了当前选择的奖项
          return !winner.prizes.includes(currentPrize);
        }
        return true;
      });
    },
    allPrizes() {
      const prizes = [
        { 
          key: 'firstPrize', 
          name: '一等奖',
          total: this.form.firstPrize,
          used: (this.$store.state.presetWinners ? 
            Object.values(this.$store.state.presetWinners)
              .filter(prizes => prizes.includes('firstPrize')).length : 0)
        }
      ];
      
      this.storeNewLottery.forEach(item => {
        const used = this.$store.state.presetWinners ? 
          Object.values(this.$store.state.presetWinners)
            .filter(prizes => prizes.includes(item.key)).length : 0;
        prizes.push({
          key: item.key,
          name: item.name,
          total: this.form[item.key],
          used: used
        });
      });
      
      return prizes;
    },
    hasAvailablePrizes() {
      return this.allPrizes.some(prize => prize.used < prize.total);
    },
    getMaxSelectCount() {
      // 获取当前选中奖项的剩余名额
      if (!this.presetForm.prizes) return 0;
      const prizeInfo = this.allPrizes.find(p => p.key === this.presetForm.prizes);
      return prizeInfo ? prizeInfo.total - prizeInfo.used : 0;
    },
    excludedListData() {
      return this.excludedList.map(number => ({
        number
      }));
    },
    totalPrizeCount() {
      // 计算所有奖项总数
      let total = Number(this.form.firstPrize || 0);
      this.storeNewLottery.forEach(item => {
        total += Number(this.form[item.key] || 0);
      });
      return total;
    },
    maxExcludedCount() {
      // 计算最大可排除人数 = 总人数 - 总奖项数
      return Math.max(0, this.list.length - this.totalPrizeCount);
    },
    availableExcludedList() {
      return this.list.filter(item => {
        // 过滤掉已经在当前奖项排除名单中的人
        const currentExcluded = this.$store.state.excludedList[this.excludedForm.prize] || [];
        return !currentExcluded.includes(item.key);
      });
    },
    remainingExcludeCount() {
      return this.maxExcludedCount - this.excludedList.length;
    },
    hasExcludedPeople() {
      return Object.keys(this.$store.state.excludedList).length > 0;
    },
    allExcludedListData() {
      const excludedList = this.$store.state.excludedList;
      const data = [];
      Object.entries(excludedList).forEach(([prize, numbers]) => {
        numbers.forEach(number => {
          data.push({
            prize,
            number
          });
        });
      });
      return data;
    },
    currentPrizeMaxExcluded() {
      if (!this.excludedForm.prize) return 0;
      const prize = this.allPrizes.find(p => p.key === this.excludedForm.prize);
      if (!prize) return 0;
      // 当前奖项最多可排除人数 = 总人数 - 该奖项总数
      return Math.max(0, this.list.length - prize.total);
    },
    isExceedLimit() {
      return this.excludedForm.numbers.length > this.currentPrizeMaxExcluded;
    },
    totalExcludedCount() {
      const excludedList = this.$store.state.excludedList;
      let total = 0;
      Object.values(excludedList).forEach(numbers => {
        total += numbers.length;
      });
      return total;
    }
  },
  data() {
    return {
      showAddLottery: false,
      newLottery: { name: '' },
      presetDialogVisible: false,
      presetForm: {
        prizes: '',
        numbers: []
      },
      presetRules: {
        prizes: [
          { required: true, message: '请选择预设奖项', trigger: 'change' }
        ],
        numbers: [
          { type: 'array', required: true, message: '请选择员工', trigger: 'change' }
        ]
      },
      excludedList: this.$store.state.excludedList || [],
      excludedDialogVisible: false,
      excludedForm: {
        numbers: [],
        prize: ''
      },
      showFirstPrizeEdit: false
    };
  },
  methods: {
    onSubmit() {
      const config = Object.assign({}, this.form);
      setData(configField, config);
      this.$store.commit('setConfig', config);
      this.$message({
        message: '保存成功',
        type: 'success'
      });
      this.$emit('resetconfig');
      this.$emit('update:visible', false);
    },
    addLottery() {
      this.showAddLottery = true;
    },
    randomField() {
      const str = 'abcdefghijklmnopqrstuvwxyz';
      let fieldStr = '';
      for (let index = 0; index < 10; index++) {
        fieldStr += str.split('')[randomNum(1, 27) - 1];
      }
      return `${fieldStr}${Date.now()}`;
    },
    addHandler() {
      const field = this.randomField();
      const data = {
        key: field,
        name: this.newLottery.name
      };
      this.$store.commit('setNewLottery', data);

      this.showAddLottery = false;
    },
    checkPresetPermission() {
      if (!this.$store.state.isAdmin) {
        this.$message.error('您没有预设中奖人的权限');
        return false;
      }
      return true;
    },
    addPresetWinner() {
      if (!this.presetForm.numbers.length) {
        this.$message.warning('请选择要预设的员工');
        return;
      }

      // 检查是否超过奖项名额
      const maxCount = this.getMaxSelectCount;
      if (this.presetForm.numbers.length > maxCount) {
        this.$message.warning(`当前奖项最多还可预设${maxCount}人`);
        return;
      }

      this.presetForm.numbers.forEach(number => {
        this.$store.commit('setPresetWinner', {
          number: Number(number),
          prizes: [this.presetForm.prizes]  // 包装成数组传递
        });
      });

      this.presetDialogVisible = false;
      this.presetForm = { prizes: '', numbers: [] };
      this.$message.success('添加预设成功');
    },
    removePreset(number) {
      if (!this.checkPresetPermission()) return;
      this.$store.commit('removePresetWinner', number);
    },
    clearPresetWinners() {
      this.$confirm('确定要清空所有预设中奖数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.commit('clearPresetWinners');
        this.$message.success('预设中奖数据已清空');
      }).catch(() => {});
    },
    showPresetDialog() {
      if (!this.list.length) {
        this.$message.warning('请先导入名单');
        return;
      }
      if (!this.availablePrizes.length) {
        this.$message.warning('请先添加奖项');
        return;
      }
      this.presetDialogVisible = true;
    },
    
    getPersonInfo(number) {
      const person = this.list.find(item => item.key === Number(number));
      return {
        name: person ? person.name : ''
      };
    },
    
    getPrizeNames(prizes) {
      return prizes.map(key => {
        if (key === 'firstPrize') return this.form.firstPrizeName || '一等奖';
        const prize = this.storeNewLottery.find(item => item.key === key);
        return prize ? prize.name : key;
      });
    },
    
    goToImportList() {
      this.presetDialogVisible = false;
      // 触发打开导入名单的事件
      this.$emit('openImportList');
    },
    getPersonName(number) {
      const person = this.list.find(item => item.key === number);
      return person ? person.name : '';
    },
    submitPresetForm() {
      this.$refs.presetForm.validate((valid) => {
        if (valid) {
          this.addPresetWinner();
        }
      });
    },
    showExcludedDialog() {
      if (!this.list.length) {
        this.$message.warning('请先导入名单');
        return;
      }
      if (this.excludedList.length >= this.maxExcludedCount) {
        this.$message.warning(`已达到最大排除人数(${this.maxExcludedCount}人)，必须保留足够的可抽奖人数(${this.totalPrizeCount}人)`);
        return;
      }
      this.excludedDialogVisible = true;
    },
    submitExcludedForm() {
      if (!this.excludedForm.prize) {
        this.$message.warning('请选择要排除的奖项');
        return;
      }
      if (!this.excludedForm.numbers.length) {
        this.$message.warning('请选择要排除的员工');
        return;
      }

      // 获取当前奖项的排除名单
      const excludedList = { ...this.$store.state.excludedList };
      const currentExcluded = excludedList[this.excludedForm.prize] || [];
      
      // 检查是否超过当前奖项可排除人数
      if (currentExcluded.length + this.excludedForm.numbers.length > this.currentPrizeMaxExcluded) {
        this.$message.warning(`该奖项最多只能排除${this.currentPrizeMaxExcluded}人，必须保留足够的可抽奖人数`);
        return;
      }

      // 添加新的排除人员
      excludedList[this.excludedForm.prize] = [...new Set([...currentExcluded, ...this.excludedForm.numbers])];

      // 更新 store
      this.$store.commit('setExcludedList', excludedList);
      
      this.excludedDialogVisible = false;
      this.excludedForm = { numbers: [], prize: '' };
      this.$message.success('添加成功');
    },
    removeExcluded(prize, number) {
      const excludedList = { ...this.$store.state.excludedList };
      const numbers = excludedList[prize] || [];
      const index = numbers.indexOf(number);
      if (index > -1) {
        numbers.splice(index, 1);
        if (numbers.length === 0) {
          delete excludedList[prize];
        } else {
          excludedList[prize] = numbers;
        }
        this.$store.commit('setExcludedList', excludedList);
      }
    },
    clearExcludedList() {
      this.$confirm('确定要清空排除名单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.commit('setExcludedList', {});
        this.$message.success('排除名单已清空');
      }).catch(() => {});
    },
    isOptionDisabled(key) {
      // 如果已经在排除列表中，则不禁用（允许取消选择）
      if (this.excludedList.includes(key)) {
        return false;
      }
      // 如果已达到最大可排除数量，则禁用未选择的选项
      return this.excludedList.length >= this.maxExcludedCount;
    },
    deletePrize(prize) {
      this.$confirm(`确定要删除奖项"${prize.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除奖项
        const newLottery = this.storeNewLottery.filter(item => item.key !== prize.key);
        // 删除对应的配置
        delete this.form[prize.key];
        // 删除对应的结果
        const result = { ...this.$store.state.result };
        delete result[prize.key];
        
        // 更新 store
        this.$store.commit('setNewLottery', { type: 'reset', data: newLottery });
        this.$store.commit('setConfig', this.form);
        this.$store.commit('setResult', result);
        
        this.$message.success('删除成功');
      }).catch(() => {});
    },
    getPrizeName(key) {
      if (key === 'firstPrize') return this.form.firstPrizeName || '一等奖';
      const prize = this.storeNewLottery.find(item => item.key === key);
      return prize ? prize.name : key;
    },
    getExcludedCount(prizeKey) {
      const excludedList = this.$store.state.excludedList;
      return (excludedList[prizeKey] || []).length;
    }
  },
  watch: {
    // 当选择的奖项变化时，清空已选择的人员
    'presetForm.prizes'() {
      this.presetForm.numbers = [];
    },
    list: {
      handler(newList) {
        if (newList.length > 0) {
          // 当导入名单后，自动设置总人数为导入人数
          this.form.number = newList.length;
          this.$store.commit('setConfig', this.form);
        }
      },
      immediate: true
    },
    'form.number': {
      handler(newValue) {
        // 确保总人数不超过导入人数
        if (this.list.length > 0 && newValue > this.list.length) {
          this.form.number = this.list.length;
          this.$message.warning('总人数不能超过导入人数');
        }
      }
    },
    'excludedForm.numbers': {
      handler(newValue) {
        if (newValue.length > this.currentPrizeMaxExcluded) {
          this.$message.warning(`已超出可排除人数限制`);
        }
      },
      immediate: true
    },
    'excludedForm.prize': {
      handler(newValue) {
        if (newValue) {
          const currentExcluded = this.$store.state.excludedList[newValue] || [];
          const remainingCount = this.currentPrizeMaxExcluded - currentExcluded.length;
          if (remainingCount > 0) {
            this.$message.info(`该奖项还可以排除 ${remainingCount} 人`);
          }
        }
      }
    }
  }
};
</script>
<style lang="scss">
.c-LotteryConfig {
  .el-dialog__body {
    height: 500px;
    padding: 10px 20px;
    overflow-y: auto;
  }

  .config-container {
    display: flex;
    min-height: 100%;
    
    // 左侧配置区域
    .left-config {
      width: 300px;
      border-right: 1px solid #EBEEF5;
      padding-right: 20px;
      
      &.full-width {
        width: 100%;
        border-right: none;
        padding-right: 0;
      }
      
      .container {
        height: 100%;
        overflow-y: auto;
        padding: 0 10px;
        
        .prize-item {
          display: flex;
          flex-direction: column;
          width: 100%;
          
          .prize-name {
            font-size: 14px;
            color: #606266;
            margin-bottom: 8px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 100%;
            display: flex;
            align-items: center;
            gap: 8px;
            
            .edit-icon {
              font-size: 14px;
              color: #909399;
              cursor: pointer;
              
              &:hover {
                color: #409EFF;
              }
            }
          }
          
          .prize-input {
            display: flex;
            align-items: center;
            
            .el-input {
              flex: 1;
            }
            
            .delete-icon {
              margin-left: 10px;
              color: #F56C6C;
              cursor: pointer;
              
              &:hover {
                color: #f78989;
              }
            }
          }
        }
      }
    }
    
    // 右侧预设区域
    .right-preset {
      flex: 1;
      margin-left: 20px;
      
      .preset-container {
        display: flex;
        gap: 20px;
        min-height: 100%;
        
        .preset-winners-config,
        .excluded-list-config {
          flex: 1;
          min-height: 100%;
          background: #f5f7fa;
          border-radius: 4px;
          padding: 20px;
          display: flex;
          flex-direction: column;
          min-width: 400px;
          
          .el-table {
            margin-top: 15px;
            flex: 1;
            overflow: auto;
          }
        }
      }
    }
  }

  // 添加预设对话框样式
  .el-dialog__wrapper {
    // 主对话框的 z-index 是 2000
    &:not(:first-of-type) {
      // 确保嵌套对话框在上层
      z-index: 2001 !important;
    }
  }
}
.dialog-showAddLottery {
  .el-dialog {
    height: 186px;
  }
}
.preset-winners-config {
  margin-top: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;

  .preset-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 10px;
    
    h3 {
      margin: 0;
      font-size: 16px;
      color: #303133;
      white-space: nowrap;
    }
    
    .preset-actions {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 10px;
      
      .prize-quotas {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .el-tag {
          &:last-child {
            margin-right: 0;
          }
        }
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 40px 0;
    color: #909399;

    i {
      font-size: 48px;
      margin-bottom: 10px;
    }

    p {
      margin: 10px 0;
      font-size: 14px;
    }

    .empty-actions {
      margin-top: 20px;

      .warning-text {
        margin-right: 10px;
        color: #E6A23C;
      }
    }
  }

  .person-info {
    display: flex;
    align-items: center;
    
    .info {
      font-weight: bold;
      color: #303133;
    }
  }

  .prize-tag {
    margin: 2px 4px;
  }

  .empty-tip {
    text-align: center;
    padding: 30px 0;

    i {
      font-size: 32px;
      color: #E6A23C;
      margin-bottom: 15px;
    }

    p {
      margin: 10px 0;
      color: #606266;
    }
  }

  .el-table {
    margin: 15px 0;
    
    th {
      background-color: #f5f7fa;
      color: #606266;
    }
  }

  // 修改预设对话框样式
  .el-dialog {
    margin-top: 10vh !important;  // 调整对话框位置
  }

  .preset-actions {
    display: flex;
    align-items: center;
    
    .prize-quotas {
      margin-right: 15px;
      
      .el-tag {
        margin-right: 8px;
        
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  .form-tip {
    margin-top: 5px;
    font-size: 12px;
    &, .normal-text {
      color: #909399;
    }
    
    .warning-text {
      color: #F56C6C;
    }
  }
}
.excluded-list-config {
  .preset-header {
    .header-title {
      display: flex;
      align-items: center;
      
      h3 {
        margin: 0;
        margin-right: 8px;
      }
      
      .excluded-total {
        color: #909399;
        font-size: 13px;
        cursor: help;
        
        &:hover {
          color: #409EFF;
        }
      }
    }
  }
}
.dialog-title {
  display: flex;
  align-items: center;
  
  .excluded-count {
    margin-left: 10px;
    color: #909399;
    font-size: 13px;
    cursor: help;
    
    &:hover {
      color: #409EFF;
    }
  }
}
</style>
